package com.huayun.code;

import com.huayun.code.core.extractor.ITableExtractor;
import com.huayun.code.core.gen.CodeGenerator;
import com.huayun.code.core.model.Table;
import com.huayun.code.core.utils.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MainGen implements CommandLineRunner {

    public static boolean test = false;

    private static final Logger LOG = LoggerFactory.getLogger(Component.class);

    @Autowired
    private ITableExtractor tableExtractor;

    @Autowired
    private List<CodeGenerator> codegens;

    @Value("${code-gen.template-location}")
    private String prefix;

    public void run(String... args) throws Exception {
        LOG.info("args...{}", args);
        try {
            String[] tableNames = ConfigUtils.getTables();

            for (String tableName : tableNames) {
                Table table = tableExtractor.getTable(tableName);
                LOG.info("表名:{} 查询结果:{}", tableName, table);

                for (CodeGenerator gen : codegens) {
                    if (!templateExists(gen.getClass().getSimpleName() + ".txt")) {
                        continue;
                    }
                    gen.setTable(table.clone());
                    LOG.info("文件路径:{}", gen.getFilePath());
                    if (ConfigUtils.getConsole()) {
                        System.out.println(gen.generate());
                    }
                    gen.generate(gen.getFilePath());
                }
            }
        } finally {
            if (test) {
                System.exit(1);
            }
        }
    }

    private boolean templateExists(String name) {
        String path = prefix + name;
        ClassPathResource cpr = new ClassPathResource(path);
        return cpr.exists();
    }

}
